/*
 * Copyright (C) 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.www.coroutinestartdemo.main

import android.content.Context
import androidx.work.CoroutineWorker
import androidx.work.ListenableWorker
import androidx.work.WorkManager
import androidx.work.Worker
import androidx.work.WorkerFactory
import androidx.work.WorkerParameters

/**
 * 当应用程序在后台时，Worker job从网络刷新标题。
 * WorkManager是一个库，用于对保证在满足约束后执行的工作进行排队。
 * 它可以运行工作，甚至当应用程序在后台，或不运行。
 */
class RefreshMainDataWork(
    context: Context,
    params: WorkerParameters,
    private val network: MainNetwork
) :
    CoroutineWorker(context, params) {

    /**
     * 使用TitleRepository从网络刷新标题
     * WorkManager将从后台线程调用这个方法。
     * 即使在我们的应用程序被操作系统终止后，它也可能被调用，
     * 在这种情况下，WorkManager将启动刚好足够运行这个Worker。
     */
    override suspend fun doWork(): Result {
        return Result.success()         // TODO: Use coroutines from WorkManager
    }

    class Factory(val network: MainNetwork = getNetworkService()) : WorkerFactory() {
        override fun createWorker(
            appContext: Context,
            workerClassName: String,
            workerParameters: WorkerParameters
        ): ListenableWorker? {
            return RefreshMainDataWork(appContext, workerParameters, network)
        }

    }
}